﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace CPAIS.Web
{
    /// <summary>
    /// Represents a node in route map table.
    /// </summary>
   public struct RouteNode
    {
        public Type HandlerType;
        public MethodInfo ActionInfo;
    }

    public class Global : System.Web.HttpApplication
    {        
        private Dictionary<int, RouteNode> LoadRouteMapConfig(string pathName)
        { 
            Dictionary<int, RouteNode> routeMap = new Dictionary<int,RouteNode>();
            DataSet dataSet = new DataSet();
            dataSet.ReadXml(pathName);
            var dataRows = dataSet.Tables[0].Rows;
            foreach (DataRow item in dataRows)
            {
                string actionName = item[Constants.Action].ToString().Trim();
                string typeName = item[Constants.Type].ToString().Trim();

                Type handlerType = Type.GetType(typeName);
                if (handlerType == null)
                    throw new Exception(string.Format("Type of '{0}' is not existed", typeName));

                MethodInfo actionInfo = handlerType.GetMethod(actionName);
                if (actionInfo == null)
                    throw new Exception(string.Format("Method of '{0}' is not existed in type of '{1}'",
                        actionName, typeName));

                routeMap.Add(actionName.GetHashCode(), new RouteNode
                {
                    HandlerType = handlerType,
                    ActionInfo = actionInfo
                });
            }

            return routeMap;
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            Application.Add(Constants.RouteMap, LoadRouteMapConfig(HttpContext.Current.Server.MapPath(Constants.RouteMapXml)));
            Application.Add(Constants.DSManager, new DSManager());
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Session.Add(Constants.MLManager, new MLManager());
        }

        protected void Session_End(object sender, EventArgs e)
        {
            Session.RemoveAll();
        }

        protected void Application_End(object sender, EventArgs e)
        {
            Application.RemoveAll();
        }
    }
}